package com.luoqy.speedy.modular.web.service.impl;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.luoqy.speedy.modular.web.mapper.ChapterContentMapper;
import com.luoqy.speedy.modular.web.mapper.ChapterMapper;
import com.luoqy.speedy.modular.web.model.Chapter;
import com.luoqy.speedy.modular.web.model.ChapterContent;
import com.luoqy.speedy.modular.web.model.Fiction;
import com.luoqy.speedy.modular.web.service.IChapterService;
import com.luoqy.speedy.modular.web.service.IFictionService;
import com.luoqy.speedy.modular.web.service.UpdateFictionService;
import com.luoqy.speedy.modular.web.utils.JsoupUtil;

@Service
public class UpdateFictionServiceImpl implements UpdateFictionService {

	@Resource
	private IFictionService iFictionService;

	@Resource
	private IChapterService iChapterService;

	@Resource
	private ChapterMapper chapterMapper;

	@Resource
	private ChapterContentMapper chapterContentMapper;
	/**
	 * 更新基础书籍信息
	 * */
	@Override
	public void updateFictionBase(Fiction fiction){

		QueryWrapper<Chapter> queryWrapper = new QueryWrapper<Chapter>();
		if (null == fiction.getIsupdate()) {
			fiction.setIsupdate(0);
		}
		queryWrapper.eq("fiction_id", fiction.getId());
		List<Chapter> list = iChapterService.list(queryWrapper);
		int catLength = list.size();
		Document doc = JsoupUtil.getDoc(fiction.getFictionUrl());
		if (null != doc) {
			Elements elements = doc.select("dd>a");
			int elnLength = elements.size() - 12;
			//查询是否有更新臧姐
			if (catLength != elnLength && 1 == fiction.getIsupdate()) {
				System.err.println(fiction.getFictionName()+"***进行基础资料更新同步");
				iFictionService.updateById(fiction);
			} 
		}
	
	}
	/**
	 * 根据小说章节页面链接更新小说内容
	 * */
	@Async
	// @Transactional(rollbackFor = RuntimeException.class)
	@Override
	public void updateFiction(Fiction fiction) {
		try {
			QueryWrapper<Chapter> queryWrapper = new QueryWrapper<Chapter>();
			if (null == fiction.getIsupdate()) {
				fiction.setIsupdate(0);
			}
			queryWrapper.eq("fiction_id", fiction.getId());
			List<Chapter> list = iChapterService.list(queryWrapper);
			int catLength = list.size();
			Document doc = JsoupUtil.getDoc(fiction.getFictionUrl());
			if (null != doc) {
				Elements elements = doc.select("dd>a");
				int elnLength = elements.size() - 12;
				if (catLength != elnLength && 0 == fiction.getIsupdate()) {
					System.err.println(fiction.getFictionName()+"***进行全量更新同步");
					chapterMapper.delete(queryWrapper);
					int sort = 1;
					int cot = 0;
					for (Element element : elements) {
						ChapterContent chapterContent = new ChapterContent();
						if (cot < 12) {
							cot++;
							continue;
						}
						String url = element.attr("abs:href");
						Document document = JsoupUtil.getDoc(url);
						if (null != document) {
							String title = document.select("h1").text();// 章节标题
							String text = document.getElementById("content").html();// 章节内容
							// 保存小说内容
							chapterContentMapper.insert(chapterContent.setContent(text));
	
							chapterMapper.insert(new Chapter(url, fiction.getId(), title, sort, chapterContent.getId()));
							sort++;
						}
					}
					fiction.setIsupdate(1);
					iFictionService.updateById(fiction);
					System.err.println(fiction.getFictionName()+"***全量更新同步完成");
				} else if (catLength != elnLength && 1 == fiction.getIsupdate()) {
					System.err.println(fiction.getFictionName()+"***进行最新章节更新同步");
					// 有更新
					ChapterContent chapterContent = new ChapterContent();
					int i = elements.size() - catLength - 12;
					int sort = catLength + 1;
					int k = catLength + 12;// 最新章节下标
	
					for (int j = 0; j < i; j++) {
	
						String url = elements.get(k).attr("abs:href");
						Document document = JsoupUtil.getDoc(url);
						if (null != document) {
							Chapter chapter = new Chapter();
							String title = document.select("h1").text();// 章节标题
							String text = document.getElementById("content").html();// 章节内容
							// 保存小说内容
							chapterContentMapper.insert(chapterContent.setContent(text));
							chapter.setChapterUrl(url);
							chapter.setFictionId(fiction.getId());
							chapter.setChapterTitle(title);
							chapter.setSort(sort);
							chapter.setContentId(chapterContent.getId());// 章节内容id
							chapter.setCreateDate(new Date());
							chapterMapper.insert(chapter);
							k++;
							sort++;// 排序
							// 设置最新章节
							fiction.setNewest(title);
							// 更新时间
							fiction.setCreateDate(new SimpleDateFormat("YYYY-MM-dd HH:mm:ss").format(new Date()));
							// 更新最新章节
							iFictionService.updateById(fiction);
						}
					}
					System.err.println(fiction.getFictionName()+"***最新章节更新同步完成");
				} else {
					if(0==fiction.getIsupdate()){
						fiction.setIsupdate(1);
						iFictionService.updateById(fiction);
					}
					System.err.println(fiction.getFictionName() + "小说已经是最新");
				}
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
	}
}
